package com.asktgapp.user.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.TextView;

import com.asktgapp.JGTool.Utils;
import com.asktgapp.R;
import com.asktgapp.application.ApiUtil;
import com.asktgapp.application.Apiservice;
import com.asktgapp.architecture.retrofit.ApiException;
import com.asktgapp.architecture.retrofit.ApiResponseBody;
import com.asktgapp.architecture.rxjava.ExceptionHandle;
import com.asktgapp.base.BaseFragment;
import com.asktgapp.model.QiuZuDetailVO;
import com.asktgapp.model.UsedMachineDetailVO;
import com.asktgapp.modulebase.common.util.PreferencesUtil;
import com.asktgapp.user.activity.ShareActivity;
import com.asktgapp.widget.UseMachinDetailBanner;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.ButterKnife;
import butterknife.InjectView;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * time:2018/1/23
 * Create By ZhaoKai
 * Email: dczk@foxmail.com
 * Description:
 */

public class QiuZuDetailFragment extends BaseFragment {

    @InjectView(R.id.tv_used_machine_name)
    TextView mTitle;
    @InjectView(R.id.tv_price)
    TextView mPrice;
    @InjectView(R.id.tv_add_time)
    TextView mTime;
    @InjectView(R.id.tv_model)
    TextView mModel;
    @InjectView(R.id.tv_address)
    TextView mAddress;
    @InjectView(R.id.tv_count)
    TextView mCount;
    @InjectView(R.id.tv_work_time)
    TextView mTimeLimit;
    @InjectView(R.id.tv_pay_type)
    TextView mPayType;
    @InjectView(R.id.tv_time_arived)
    TextView mTimeArrived;
    @InjectView(R.id.tv_link_name)
    TextView mLinkName;
    @InjectView(R.id.tv_link_phone)
    TextView mLinkPhone;
    @InjectView(R.id.tv_info)
    TextView mInfo;
    @InjectView(R.id.tv_tonnage)
    TextView mTonnage;
    @InjectView(R.id.tv_brand)
    TextView mBrand;
    @InjectView(R.id.ff_sendSMS)
    FrameLayout mSendSMS;
    @InjectView(R.id.ff_callPhone)
    FrameLayout mCallPhone;
    @InjectView(R.id.tv_guanzhu)
    TextView mGuanzhu;
    private String machineId;
//    private String priceUnit = "元";

    private QiuZuDetailVO.DataInfoBean usedMachine;
    private boolean isFollow = false;

    private void setUI(QiuZuDetailVO.DataInfoBean bean) {
        mTitle.setText(bean.getTitle());
        mPrice.setText(Utils.D2I(bean.getPrice()) + bean.getPrice_unit() + "");
        mTime.setText(Utils.getDateAll(bean.getAdd_time()));
        mModel.setText(bean.getModel());
        mAddress.setText(bean.getPro_name().replace("省", "") + " " + bean.getCity_name());
        mCount.setText(bean.getNumber() + "台");
        mTimeLimit.setText(bean.getTime_limit() + "天");
        mTonnage.setText(String.valueOf(Utils.DtS(bean.getTonnage())));
        mLinkName.setText(bean.getLink_name());
        mLinkPhone.setText(bean.getLink_phone());
        mInfo.setText(bean.getInfo());
        mBrand.setText(bean.getBrand());
        mTimeArrived.setText(Utils.getDateYMD(bean.getEnd_time()));
        //结款方式 0:现款 1:工程结束 2:协商付款
        if (bean.getPay_type() == 0) {
            mPayType.setText("现款");
        } else if (bean.getPay_type() == 1) {
            mPayType.setText("工程结束");
        } else {
            mPayType.setText("协商付款");

        }
        //0没有关注 1关注
        if (bean.getIs_follow() == 0) {
            isFollow = false;
            mGuanzhu.setCompoundDrawablesWithIntrinsicBounds(0, R.mipmap.weiguanzhu, 0, 0);
            mGuanzhu.setText("未关注 ");
        } else {
            isFollow = true;
            mGuanzhu.setCompoundDrawablesWithIntrinsicBounds(0, R.mipmap.yiguanzh, 0, 0);
            mGuanzhu.setText("已关注");
        }
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        ViewGroup viewGroup = (ViewGroup) inflater.inflate(R.layout.fragment_qiuzu_detail, container, false);
        ButterKnife.inject(this, viewGroup);
        return super.onCreateView(inflater, viewGroup, savedInstanceState);
    }

    @Override
    protected void initView(View rootView) {
        getBaseActivity().setBackNavigationIcon();
        setHasOptionsMenu(true);
        machineId = getActivity().getIntent().getStringExtra("id");
        mCallPhone.setOnClickListener(this);
        mSendSMS.setOnClickListener(this);
        mGuanzhu.setOnClickListener(this);

    }

    private void doFollow(int i) {
        Apiservice apiservice = ApiUtil.getInstance().create();
        HashMap params = new HashMap();
        params.put("userid", PreferencesUtil.getString(getActivity(), PreferencesUtil.USER_ID));
        //0:二手机 1:设备出租 2:设备求租 3:工程师
        params.put("type", 2);
        params.put("temp", i);
        params.put("id", machineId);
        showProgress(getClass().getSimpleName());
        Call<ApiResponseBody> call = apiservice.follow(params);
        call.enqueue(new Callback<ApiResponseBody>() {
            @Override
            public void onResponse(Call<ApiResponseBody> call, Response<ApiResponseBody> response) {
                dismissProgress();
                if (response.isSuccessful()) {
                    if (isFollow) {
                        mGuanzhu.setCompoundDrawablesWithIntrinsicBounds(0, R.mipmap.weiguanzhu, 0, 0);
                        mGuanzhu.setText("未关注 ");
                    } else {
                        mGuanzhu.setCompoundDrawablesWithIntrinsicBounds(0, R.mipmap.yiguanzh, 0, 0);
                        mGuanzhu.setText("已关注");
                    }
                    isFollow = !isFollow;
                } else {
                    showTost(response.raw().message(), 1);
                }
            }

            @Override
            public void onFailure(Call<ApiResponseBody> call, Throwable t) {
                dismissProgress();
                ApiException apiException = ExceptionHandle.handleException(t);
                if (apiException.isTokenInvalid()) {
                    showUnLoginSnackbar();
                } else if (apiException.isNetConnected()) {
                    showSetNetworkSnackbar();
                } else {
                    showTost(apiException.getMessage(), 0);
                }
            }
        });
    }

    @Override
    public void loadData() {
        visibleLoading();
        Apiservice apiservice = ApiUtil.getInstance().create();
        HashMap params = new HashMap();
        params.put("userid", PreferencesUtil.getString(getActivity(), PreferencesUtil.USER_ID));
        params.put("id", machineId);
        //出租
        params.put("type", 1);
        Call<ApiResponseBody<QiuZuDetailVO>> call = apiservice.getQiuZuDetail(params);
        call.enqueue(new Callback<ApiResponseBody<QiuZuDetailVO>>() {
            @Override
            public void onResponse(Call<ApiResponseBody<QiuZuDetailVO>> call, Response<ApiResponseBody<QiuZuDetailVO>> response) {
                inVisibleLoading();
                if (response.isSuccessful()) {
                    usedMachine = response.body().getResult().getDataInfo();
                    setUI(usedMachine);
                } else {
                    showTost(response.raw().message(), 1);
                }
            }

            @Override
            public void onFailure(Call<ApiResponseBody<QiuZuDetailVO>> call, Throwable t) {
                inVisibleLoading();
                ApiException apiException = ExceptionHandle.handleException(t);
                if (apiException.isTokenInvalid()) {
                    showUnLoginSnackbar();
                } else if (apiException.isNetConnected()) {
                    showSetNetworkSnackbar();
                } else {
                    showTost(apiException.getMessage(), 0);
                }

            }
        });
    }


    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.reset(this);
    }

    @Override
    public void onPause() {
        super.onPause();
    }

    @Override
    public void onResume() {
        super.onResume();
    }

    @Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        inflater.inflate(R.menu.share, menu);
        super.onCreateOptionsMenu(menu, inflater);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        Intent intent = new Intent(getActivity(), ShareActivity.class);
        intent.putExtra("type", 2);
        intent.putExtra("id", String.valueOf(usedMachine.getId()));
        startActivity(intent);
        return super.onOptionsItemSelected(item);
    }

    @Override
    public void onClick(View v) {
        super.onClick(v);
        switch (v.getId()) {
            case R.id.ff_sendSMS:
                if (checkIsLogin("登录后可查看更多内容"))
                    Utils.sendMessage(getActivity(), usedMachine.getLink_phone());
                break;
            case R.id.ff_callPhone:
                if (checkIsLogin("登录后可查看更多内容"))
                    Utils.callPhone(getActivity(), usedMachine.getLink_phone());
                break;
            case R.id.tv_guanzhu:
                //0取消关注 1关注
                if (isFollow) {
                    doFollow(0);
                } else {
                    doFollow(1);
                }

                break;
        }
    }
}
